package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.WustDown;
import com.linghang.demo.domain.WustDownExample;
import com.linghang.demo.mapper.WustDownMapper;
import com.linghang.demo.req.WustdownQueryReq;
import com.linghang.demo.resp.WustdownQueryResp;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Service
public class WustdownService {
    private int id=10;
    @Resource
    private WustDownMapper wustdownMapper;
    private static final Logger LOG = LoggerFactory.getLogger(WustdownService.class);

    public List<WustDown> list(){
        return wustdownMapper.selectByExample(null);
    }

    public PageResp<WustdownQueryResp> list(WustdownQueryReq req) {
        WustDownExample wustdownExample = new WustDownExample();
        WustDownExample.Criteria criteria = wustdownExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<WustDown> wustdownList = wustdownMapper.selectByExample(wustdownExample);

        PageInfo<WustDown> pageInfo = new PageInfo<>(wustdownList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<WustDownResp> respList = new ArrayList<>();
        // for (WustDown wustdown : wustdownList) {
        //     // WustDownResp wustdownResp = new WustDownResp();
        //     // BeanUtils.copyProperties(wustdown, wustdownResp);
        //     // 对象复制
        //     WustDownResp wustdownResp = CopyUtil.copy(wustdown, WustDownResp.class);
        //
        //     respList.add(wustdownResp);
        // }

        // 列表复制
        List<WustdownQueryResp> list = CopyUtil.copyList(wustdownList, WustdownQueryResp.class);

        PageResp<WustdownQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(@Valid WustdownQueryReq req) {
        WustDown wustdown= CopyUtil.copy(req, WustDown.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            wustdown.setId(id++);
            wustdownMapper.insert(wustdown);
        } else {
            // 更新
            wustdownMapper.updateByPrimaryKey(wustdown);
        }
    }

    
    public void  delete(int id){
        wustdownMapper.deleteByPrimaryKey(id);
    }
}
